package com.qinggeng.project.system.service.impl;

import com.qinggeng.common.exception.CustomException;
import com.qinggeng.common.utils.StringUtils;
import com.qinggeng.framework.redis.RedisCache;
import com.qinggeng.project.system.domain.GsdRequestUrl;
import com.qinggeng.project.system.mapper.GsdRequestUrlMapper;
import com.qinggeng.project.system.service.GsdRequestUrlService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.testng.annotations.IFactoryAnnotation;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class GsdRequestUrlServiceImpl implements GsdRequestUrlService {

    @Autowired
    private GsdRequestUrlMapper gsdRequestUrlMapper;
    @Resource
    private RedisCache redisCache;


    public static  final String GSD_REQUEST_INIT_KEY="GSD_REQUEST_INIT_KEY:";

    @Override
    public String getRequestInitUrl() {
        String url="";
        try {
            url= redisCache.getCacheObject(GSD_REQUEST_INIT_KEY);
            if (StringUtils.isNotEmpty(url)){
                return  url;
            }
        }catch (Exception e){
            log.error("getRequestInitUrl Exception {}",e.getMessage());
        }
        GsdRequestUrl gsdRequestUrl=getGsdRequestUrl();
        if (null ==gsdRequestUrl){
            throw  new CustomException("系统未设置地址");
        }
        url = gsdRequestUrl.getUrl();
        try {
            redisCache.setCacheObject(GSD_REQUEST_INIT_KEY,url,1, TimeUnit.HOURS);
        }catch (Exception e){
            log.error("getRequestInitUrl Exception {}",e.getMessage());

        }
        return  url;
    }

    private  GsdRequestUrl getGsdRequestUrl(){
        Example example=new Example(GsdRequestUrl.class);
        example.createCriteria()
                .andEqualTo("type",0)
                .andEqualTo("status",0);
        GsdRequestUrl gsdRequestUrl=gsdRequestUrlMapper.selectOneByExample(example);
        return  gsdRequestUrl;
    }
    @Override
    public boolean loadRequestUrl() {


        return redisCache.deleteObject(GSD_REQUEST_INIT_KEY);
    }

    @Override
    public List<GsdRequestUrl> list() {

        return gsdRequestUrlMapper.selectAll();
    }

    @Override
    public boolean updateRequestUrl(GsdRequestUrl gsdRequestUrl) {
        Long id=gsdRequestUrl.getId();
        if (null == id){
            throw  new CustomException("id is  null");
        }
        loadRequestUrl();
        return gsdRequestUrlMapper.updateByPrimaryKeySelective(gsdRequestUrl)>=1;
    }
}
